package com.hnevc.homework;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.hnevc.homework.adapter.NewsAdapter;
import com.hnevc.homework.bean.NewsBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {


    private ListView lv_news;
    private List<NewsBean.ResultBean.DataBean> list;
    private String url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_layout);
        initView();
        initDate();


    }

    private void initDate() {
        url = "http://v.juhe.cn/toutiao/index?key=368cf096b8c3c4b53dbc664c686b3a6d";

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("type","top");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,
                jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                Log.e("TAG", "onResponse: " + jsonObject.toString());
                Gson gson = new Gson();
                NewsBean dataBean = gson.fromJson(jsonObject.toString(), NewsBean.class);
                list.addAll(dataBean.getResult().getData());
                Log.e("TAG", "onResponse: " + list.toString());
                NewsAdapter newsAdapter = new NewsAdapter(list, MainActivity.this);
                lv_news.setAdapter(newsAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MainActivity.this, "网络请求失败！", Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonObjectRequest);

    }

    private void initView() {
        lv_news = (ListView) findViewById(R.id.lv_news);
        list = new ArrayList<>();
    }
}